package com.geekgo.gges.util;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.GeoDistanceQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.core.query.StringQuery;

/**
 * Created by Administrator on 2018/4/28.
 */
public class ESQueryUtil {


    /**
     * 字符串的查询
     * @param searchContent 查询字符串
     * @return
     */
    public static SearchQuery stringQuery(String searchContent){
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.queryStringQuery(searchContent)).build();
        return searchQuery;
    }

    /**
     *
     * @param searchContent 过滤条件（xxx=111,aaa=222）
     * @param matchPhrase true 使用，短语精准匹配
     * @return
     */
    public static QueryBuilder boolQuery(String searchContent,boolean matchPhrase){
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //搜索的的字段
        if (StringUtils.isNotEmpty(searchContent)) {
            for (String s : searchContent.split(",")) {
                String[] ss = s.split("=");
                if (ss.length > 1) {
                    if (matchPhrase == Boolean.TRUE) {
                        boolQuery.must(QueryBuilders.matchPhraseQuery(s.split("=")[0], s.split("=")[1]));
                    } else {
                        boolQuery.must(QueryBuilders.matchQuery(s.split("=")[0], s.split("=")[1]));
                    }
                }

            }
        }
        return boolQuery;
    }

    /**
     * 地理范围
     * @param lat 维度
     * @param lon 经度
     * @param distance 查询某经纬度distance米范围内
     * @return
     */
    public SearchQuery geoQuery(double lat,double lon,double distance){
        //查询某经纬度distance米范围内
        GeoDistanceQueryBuilder builder = QueryBuilders.geoDistanceQuery("address").point(lat, lon)
                .distance(distance, DistanceUnit.METERS);

        GeoDistanceSortBuilder sortBuilder = SortBuilders.geoDistanceSort("address",lat,lon)
                .unit(DistanceUnit.METERS)
                .order(SortOrder.ASC);

        Pageable pageable = PageRequest.of(0,50);

        NativeSearchQueryBuilder builder1 = new NativeSearchQueryBuilder().withFilter(builder).withSort(sortBuilder).withPageable(pageable);
        SearchQuery searchQuery = builder1.build();
        return searchQuery;
    }
}
